package com.op.studyingliteapp.activity.sonseminar;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.op.studyingliteapp.R;
import com.op.studyingliteapp.activity.ScreenshotActivity;
import com.op.studyingliteapp.bean.SeminarBean;
import com.op.studyingliteapp.common.Common;
import com.op.studyingliteapp.common.SeminarsUrl;
import com.op.studyingliteapp.database.dao.SeminarDao;
import com.op.studyingliteapp.sender.Runtime;
import com.op.studyingliteapp.sender.ui.view.device.DeviceScanDialog;
import com.op.util.ScreenSendUtils;
import com.op.util.StringUtils;
import com.op.util.asynctask.HttpPostTask;
import com.op.util.asynctask.OnTaskProcessListener;

public class sonSeminarActivity extends ScreenshotActivity{

	private final static String TAG = sonSeminarActivity.class.getSimpleName();
	private sonSeminarAdapter madapter;
	private ArrayList<sonSeminarData> moreList = new ArrayList<sonSeminarData>();
	private String getuserId, getCourseId;
	private SharedPreferences preferences;
	private ListView listView;
	private EditText editText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_son_seminar);
		com.op.studyingliteapp.sender.Runtime
				.setView(findViewById(R.id.LinearLayout));

		// 更改actionbar title
		ActionBar actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle("交流");

		preferences = getSharedPreferences("StudyingLite", Context.MODE_PRIVATE);
		getuserId = preferences.getString(Common.Prefs.USER_ID, "");
		getCourseId = preferences.getString(Common.Prefs.COURSE_ID, "");
		editText = (EditText) findViewById(R.id.reply);
		setOverflowShowingAlways();

		downLoadData();
		setListView();
		replay();
	}

	/**
	 * 解决overflow按钮的显示情况和手机的硬件情况是有关系的， 如果手机没有物理Menu键的话，overflow按钮就可以显示，
	 * 如果有物理Menu键的话，overflow按钮就不会显示出来
	 */
	private void setOverflowShowingAlways() {
		try {
			ViewConfiguration config = ViewConfiguration.get(this);
			Field menuKeyField = ViewConfiguration.class
					.getDeclaredField("sHasPermanentMenuKey");
			menuKeyField.setAccessible(true);
			menuKeyField.setBoolean(config, false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setListView() {
		listView = (ListView) findViewById(R.id.listviewSeminar);
		madapter = new sonSeminarAdapter(this, moreList);
		listView.setAdapter(madapter);
		registerForContextMenu(listView);
	}

	// ***********************************************获取子贴内容**********************************************

	/**
	 * 从数据库获取数据 // 从数据库提取课程讨论主贴内容
	 */
	public void getDataFromDatabase() {
		SeminarDao seminarDao = new SeminarDao(sonSeminarActivity.this,
				getuserId);
		List<SeminarBean> seminar = seminarDao
				.getSeminarByCourseId(getCourseId);
		moreList.clear();
		int number = seminar.size() - 1;
		// 获取讨论标题
		for (int i = 0; i < seminar.size(); i++) {
			String title = seminar.get(i).getTitle();
			String time = seminar.get(i).getCreateTime();
			String context = seminar.get(i).getContent();
			String name = seminar.get(i).getUserBean().getName();
			String avatar = seminar.get(i).getUserBean().getImageUrl();
			String like = seminar.get(i).getLikeCount();// 点赞
			String ChildCount = seminar.get(i).getChildCount();// 评论数
			String image = seminar.get(i).getImageUrl();
			String userid = seminar.get(i).getUserBean().getId();
			String seminarId = seminar.get(i).getId();
			String seminarParentId = seminar.get(i).getParentId();
			String Pircture = seminar.get(i).getImageUrl();
			if (seminarParentId.equals("null")) {
				/*
				 * 楼主的构造方法 名字 ，头像，时间，标题，内容，图片 ,用户id,seminarId
				 */
				// moreList.add(new sonSeminarData(name, avatar, time, title,
				// context, Pircture, userid, seminarId));
				moreList.add(0, new sonSeminarData(name, avatar, time, title,
						context, Pircture, userid, seminarId));
			} else {
				/*
				 * 这是回复楼主的评论名字，头像 ，时间，回复内容 用户id,seminartId
				 */

				moreList.add(new sonSeminarData(name, avatar, time, context,
						number + "楼", userid, seminarId));
				number--;
			}

		}
		// Collections.reverse(moreList); //倒序
	}

	/**
	 * 从网上下拉json，解析，存入数据库再提取
	 */
	public void downLoadData() {
		final String getSeminarId = preferences.getString(
				Common.Prefs.SEMINAR_ID, "");

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Common.Prefs.PARENT_ID, getSeminarId));
		HttpPostTask task = new HttpPostTask(sonSeminarActivity.this,
				SeminarsUrl.GET_ROOT_AND_CHILD_SEMINARS_BY_PARENT_ID, params);
		task.setTaskListener(new OnTaskProcessListener() {
			@Override
			public void prepare() {
			}

			@Override
			public void completed(String result) {
				if (StringUtils.isEmptyOrStringNull(result)) {
					getDataFromDatabase();
				} else {
					Log.i(TAG, "解析" + result);
					// 有网络登陆时
					analyticalSeminar(result);
					getDataFromDatabase();
				}
				madapter.notifyDataSetChanged();

			}

		});
		task.execute();// 执行结束，圈转完
	}

	/**
	 * 解析主贴或子贴json，并存入数据库
	 *
	 * @param result
	 */
	public void analyticalSeminar(String result) {

		// 判断得到的数据是否为null
		if (!StringUtils.isEmptyOrStringNull(result)) {
			try {
				JSONObject jsonobjectresult = new JSONObject(result);
				String message = jsonobjectresult.getString("message");
				// 不存在parent，即主贴时
				if (message.equals("Success")) {
					SeminarDao seminarDao = new SeminarDao(
							sonSeminarActivity.this, getuserId);
					// 清空数据库
					seminarDao.empty();
					JSONObject resultMap = jsonobjectresult
							.getJSONObject("resultMap");
					JSONArray seminarList = resultMap
							.getJSONArray("seminarList");
					for (int i = 0; i < seminarList.length(); i++) {
						JSONObject seminar = new JSONObject();
						seminar = seminarList.getJSONObject(i);
						// 将JsonObject存入本地数据库
						SeminarBean seminarBean = new SeminarBean();
						seminarBean.fillAttributeByJson(seminar);
						seminarDao.insertOrUpdate(seminarBean);
					}

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	// **************************************************************************************************

	// **************************回复评论*******************************************************************

	public void replay() {

		Button send = (Button) findViewById(R.id.send);
		send.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String Content = editText.getText().toString();
				editText.setText(null);
				hideKey();
				sendToOnlineData("", Content, getCourseId);
			}
		});
	}

	public void hideKey() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
	}

	/**
	 * 发送字符串到网上数据库 Title,Content,userId,courseId，parentId 依次是标题，内容，课程id
	 */
	public void sendToOnlineData(String title, String Content, String courseId) {
		SharedPreferences preferences = getSharedPreferences("StudyingLite",
				Context.MODE_PRIVATE);
		String getUserId = preferences.getString(Common.Prefs.USER_ID, "");// 用户id
		String getSeminarId = preferences
				.getString(Common.Prefs.SEMINAR_ID, "");// 用户id
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(
				Common.Seminar.ADD_UPDATE_SEMINAR_CONTENT, Content));
		params.add(new BasicNameValuePair(
				Common.Seminar.ADD_UPDATE_SEMINAR_USER_ID, getUserId));
		params.add(new BasicNameValuePair(
				Common.Seminar.ADD_UPDATE_SEMINAR_TITLE, title));
		params.add(new BasicNameValuePair(
				Common.Seminar.ADD_UPDATE_SEMINAR_COURSE_ID, courseId));
		params.add(new BasicNameValuePair(
				Common.Seminar.ADD_UPDATE_SEMINAR_PARENT_ID, getSeminarId));

		HttpPostTask task = new HttpPostTask(sonSeminarActivity.this,
				SeminarsUrl.ADD_SEMINAR, params);
		task.setTaskListener(new OnTaskProcessListener() {

			@Override
			public void prepare() {
				// TODO Auto-generated method stub

			}

			@Override
			public void completed(String result) {
				// ToastUtils.show(getActivity(), "发布帖子成功");
				downLoadData();
				madapter.notifyDataSetChanged();
			}
		});
		task.execute();
	}

	/**
	 * 长按弹出菜单
	 * 
	 * @param menu
	 * @param v
	 * @param menuInfo
	 */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		int index = ((AdapterView.AdapterContextMenuInfo) menuInfo).position;

		sonSeminarData data = (sonSeminarData) listView
				.getItemAtPosition(index);
		if (getuserId.equals(data.getUserId())) {
			menu.add(0, 0, 0, "删除");
		}
		menu.add(0, 1, 0, "收藏");
		menu.add(0, 2, 0, "举报");
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo menuInfo;
		menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
		int index = menuInfo.position;
		switch (item.getItemId()) {
		case 0:
			delete(index);
			break;
		case 1:
			Toast.makeText(this, "待开发", Toast.LENGTH_SHORT).show();
			break;
		case 2:
			Toast.makeText(this, "待开发", Toast.LENGTH_SHORT).show();
			break;
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}

	/**
	 * 删除帖子
	 * 
	 * @param position
	 */
	private void delete(final int position) {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage("确认删除帖子吗？");
		builder.setTitle("提示");
		builder.setNeutralButton("确认", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				sonSeminarData data = madapter.getItem(position);
				madapter.deleteItem(data.getSeminarId(), data.getUserId());
				moreList.remove(position);
				// madapter.notifyDataSetChanged();
				downLoadData();
			}
		});
		builder.setNegativeButton("取消", null);
		builder.create();
		builder.show();
	}
}
